package com.tenement.netty.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.mybatisflex.core.tenant.TenantManager;
import com.tenement.common.GlobalException;
import com.tenement.entity.ChatModel;
import com.tenement.entity.User;
import com.tenement.enums.RespBusiness;
import com.tenement.netty.service.ChatHandlerService;
import com.tenement.service.ChatService;
import com.tenement.service.UserService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Set;

@Slf4j
public class ConnectServiceImpl implements ChatHandlerService {

    private UserService userService = SpringUtil.getBean(UserService.class);

    @Override
    public void execute(ChatModel chatModel, ChannelHandlerContext channelHandlerContext,
                        Map<String, Channel> privateChannel, Set<Channel> channelGroups) {
        User user = TenantManager.withoutTenantCondition(() -> userService.getById(chatModel.getUserId()));
        if (user == null) {
            throw new GlobalException(RespBusiness.NO_USER_EXISTS);
        }
        privateChannel.put(chatModel.getUserId().toString(), channelHandlerContext.channel());
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        log.info("客服端连接时间：" + format.format(new Date()) + "\t标识：" + chatModel.getUserId());
    }
}
